package com.bigdata.util;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;

import java.util.List;

    /**
     * rpc解码器
     */
    public class RpcDecoder extends MessageToMessageDecoder<ByteBuf> {

        private static final int HEAD_LENGTH = 4;

        private Class<?> clazz;
        private Serializer serializer;

        public RpcDecoder(Class<?> clazz, Serializer serializer) {
            this.clazz = clazz;
            this.serializer = serializer;
        }


        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
           // System.out.println("decode...>>>>>>>");
            if (byteBuf.readableBytes() < HEAD_LENGTH) {
                return;
            }
            byteBuf.markReaderIndex();
            int dataLength = byteBuf.readInt();
            if (dataLength < 0) {
                ctx.close();
            }
           if (byteBuf.readableBytes() < dataLength) {
                byteBuf.resetReaderIndex();
                return;
            }
            byte[] body = new byte[dataLength];
            byteBuf.readBytes(body);
            Object deserialize = serializer.deserialize(clazz, body);
           // System.out.println("deserialize"+deserialize);
            out.add(deserialize);
        }
    }